import {  logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

import {
  login,
  getMenu,
  getData
} from 'menucontrol'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    //权限
    menu: null,
    buttons: {}
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  //权限
  SET_MENU: (state, menu) => {
    state.menu = menu
  },
  SET_BTN: (state, btn) => {
    state.buttons = btn
  },
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { account, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ 
        username: account.trim(),
        password: password,
        app_id: process.env.VUE_APP_ADMIN_APP_ID        
      }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.accessToken)//把token存入state
        // commit('SET_NAME', data.name)//把name存入state
        localStorage.setItem("refreshToken", data.refreshToken)
        localStorage.setItem("userName", data.name)
        setToken(data.accessToken)//调用utils下的auth 使用cookie存令牌
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

//权限
getMenus({
  commit
}) {
  return new Promise((resolve, reject) => {
    getData().then(res => {
      let routers = getMenu(res.data.menu)
      // let buttons = formateButton(res.data.buttons)
      routers.push({
        path: '*',
        redirect: '/404',
        hidden: true
      })
      commit('SET_MENU', routers) //把menu存入state
      commit('SET_BTN', res.data.buttons) //把按钮权限存入state
      resolve()

    })
  })
},
  // get user info
  getInfo({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const {
          data
        } = response
        sessionStorage.setItem("data", JSON.stringify(data))
        if (!data) {
          return reject('验证失败，请重新登录')
        }

        const {
          name,
          avatar
        } = data

        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  //获取路由表
  getAntRouter({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      DongtRouter().then(response => { //请求路由表 把list结构出来
        const {
          list
        } = response.data
        if (!list) {
          reject('验证失败，请重新登录')
        }
        const arr = []
        for (let i = 0; i < list.length; i++) {
          const arrOne = list[i];
          arr.push(arrOne.permissionname)
        }
        const roles = arr
        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          reject('DongtRouter:角色必须是非空数组!')
        }
        // debugger
        commit('SET_ROLES', roles)
        resolve(roles)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // get user info
  // getInfo({ commit, state }) {
  //   return new Promise((resolve, reject) => {
  //     getInfo(state.token).then(response => {
  //       const { data } = response

  //       if (!data) {
  //         return reject('Verification failed, please Login again.')
  //       }

  //       const { name, avatar } = data

  //       commit('SET_NAME', name)
  //       commit('SET_AVATAR', avatar)
  //       resolve(data)
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

